#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
PROG=/usr/bin/alist
CONFIG=/etc/alist/config.json

get_config() {
	config_get_bool enabled $1 enabled 1
	config_get port $1 port 5244
	config_get expiration $1 expiration 60
	config_get cleanup_interval $1 cleanup_interval 120
	config_get temp_dir $1 temp_dir "/tmp"
	config_get ssl $1 ssl 0
	config_get ssl_cert $1 ssl_cert ""
	config_get ssl_key $1 ssl_key ""
}

start_service() {
	config_load alist
	config_foreach get_config alist
	[ $enabled != 1 ] && return 1
	mkdir -p $temp_dir
	if [ "$ssl" -eq 1 ];then
		SSL=true
	else
		SSL=false
	fi
	cat > $CONFIG <<EOF
{"address":"0.0.0.0","port":$port,"assets":"/","database":{"type":"sqlite3","user":"","password":"","host":"","port":0,"name":"","table_prefix":"x_","db_file":"/etc/alist/data.db","ssl_mode":"disable"},"scheme":{"https":$SSL,"cert_file":"$ssl_cert","key_file":"$ssl_key"},"cache":{"expiration":$expiration,"cleanup_interval":$cleanup_interval},"temp_dir":"$temp_dir"}
EOF
	procd_open_instance alist
	procd_set_param command $PROG
	procd_append_param command --conf $CONFIG
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance alist
}

service_triggers() {
	procd_add_reload_trigger "alist"
}

reload_service() {
	stop
	start
}
